/**
 * 对战相关逻辑处理
 *
 *
 * @type {exports}
 */
var express = require('express');
var mongoose = require('mongoose');
var async = require('async');
var url = require('url');
var util = require('../models/util.js');
var fs = require('fs');

var Setting = require('../models/setting.js');

require('../models/user.js');
require('../models/category.js');
require('../models/store.js');
require('../models/battle.js');
require('../models/practice.js');
require('../models/paper.js');
require('../models/question.js');

var User = mongoose.model('User');
var Category = mongoose.model('Category');
var Store = mongoose.model('Store');
var Battle = mongoose.model('Battle');
var Practice = mongoose.model('Practice');
var Paper = mongoose.model('Paper');
var Question = mongoose.model('Question');

var router = express.Router();

/**
 * 删除一个对战记录
 */
router.post('/delete', function(req, res){
    console.log('delete battle ....');
    var battleId = req.query.battleId;
    console.log(req.query);
    Battle.findByIdAndRemove(battleId, {}, function(err){
        if(err){
            console.log(err);
        }
        res.send({
            succ : true
        })
    });
});

//创建一个新的对战
router.post('/new', function (req, res) {
    var query = req.query;
    var storeId = query.storeId;
    //var user = req.session.user;
    var userId = query.userId;
    User.findById(userId).exec(function(err, user){
        if(user.score < Setting.get('enrollScore')) {
            res.send({
                succ: false,
                message: '您的积分太少，不足以支付该对战的报名积分'
            });
        }else {
            Store.findOne({
                _id: storeId
            }).exec(function (err, store) {
                if (store) {
                    //随机获取一份试卷
                    Paper.count({
                        store: store._id
                    }, function(err, count){
                        var random = Math.round(Math.random() * count);
                        if(random == count){
                            random = random - 1;
                        }
                        Paper.find({
                            store: store._id
                        }).skip(random).limit(1).exec(function(err, paper){
                            if (err) {
                                console.log(err);
                            };
                            if (paper instanceof Array && paper.length > 0) {
                                console.log('随机选择的试卷:' + random + ' ' + paper[0]);
                                var battle = new Battle({
                                    store: store,
                                    paper: paper[0]._id,
                                    status: 'N', //未开始
                                    owner: userId,
                                    users: [userId],
                                    createTime: new Date()
                                });
                                battle.save(function (err) {
                                    if (err) throw err;
                                    Battle.findById(battle._id).populate('users').populate('owner').exec(function (err, b) {
                                        if (err) throw err;

                                        //对战开始时候再扣除积分
                                        res.send({
                                            succ: true,
                                            battle: b
                                        });
                                        /*
                                        //扣掉用户的参战的报名积分
                                        user.score = (user.score ? user.score : 0 ) - Setting.get('enrollScore');
                                        console.log('扣除参与对战所需的报名积分:' + user.score);
                                        if(req.session.user){
                                            req.session.user.score = user.score;
                                        }
                                        user.save(function(err){
                                            if(err) throw err;
                                            if(!store.bounty){
                                                store.bounty = 0;
                                            }
                                            store.bounty = store.bounty + Setting.get('enrollScore');
                                            console.log('题库的悬赏分增加' + store.bounty);
                                            store.save(function(err){
                                                if(err) throw err;
                                                res.send({
                                                    succ: true,
                                                    battle: b
                                                });
                                            });
                                        });
                                        */

                                    })
                                })
                            } else {
                                res.send({
                                    succ: false,
                                    message: '未找到试卷'
                                });
                            }
                        });
                    });
                } else {
                    res.send({
                        succ: false,
                        message: '错误的题库ID'
                    })
                }
            });
        }
    });

});


//加入一场对战
router.post('/join', function (req, res) {
    var query = req.query;
    console.log(query);
    var battleId = query.battleId;
    //var user = req.session.user;
    var userId = query.userId;

    Battle.findById(battleId).populate('users').exec(function (err, battle) {
        if (err) throw err;
        //检查当前用户是否已经在该对战中
        var flag = false;
        var users = battle.users || [];
        for (var i = 0; i < users.length; i++) {
            if (users[i]._id == userId) {
                flag = true;
            }
        }
        if (flag == false) { //该用户尚未加入对战
            User.findById(userId).exec(function(err, user){
                if(err) throw err;
                if(!user.score){
                    user.score = 0;
                }
                if(user.score < Setting.get('enrollScore')){
                    res.send({
                        succ : false,
                        message : '您的积分太少，不足以支付该对战的报名积分'
                    });
                }else {
                    //将用户添加到对战中
                    battle.users.push(userId);
                    battle.save(function (err) {
                        if (err) throw err;
                        res.send({
                            succ : true
                        });
                    });
                    /*
                    //支付报名积分
                    user.score = user.score - Setting.get('enrollScore');
                    if(req.session && req.session.user){
                        req.session.user.score = user.score;
                    }
                    user.save(function(err){
                        if(err) throw err;
                        battle.users.push(userId);
                        battle.save(function (err) {
                            if (err) throw err;
                            Store.findById(battle.store).exec(function(err, store){
                                if(err) throw err;
                                if(!store.bounty){
                                    store.bounty = 0;
                                }
                                store.bounty = store.bounty + Setting.get('enrollScore');
                                console.log('题库的悬赏分增加 ' + store.bounty);
                                store.save(function(err){
                                    if(err) throw err;
                                    res.send({
                                        succ : true
                                    });
                                });
                            });
                        });
                    });
                    */

                }
            });
        } else {
            res.send({
                succ: true
            })
        }
    });
});

//获取对战信息
router.post('/:battleId', function (req, res) {
    var battleId = req.params.battleId;
    Battle.findById(battleId).populate('store').populate('paper').populate('owner').populate('users').exec(function (err, battle) {
        if (err) throw err;
        battle = util.toJSON(battle);
        res.send(battle);
    });
});

//开始对战  修改对战数据状态 并返回一个试卷数据
router.post('/start/:battleId', function (req, res) {
    var battleId = req.params.battleId;

    Battle.findByIdAndUpdate(battleId, {
        status: 'I', //已经开始状态
        start: new Date()
    }).populate('users').populate('store').exec(function(err, battle){
        if(err) throw err;
        if(battle){
            var users = battle.users || [];
            var store = battle.store;
            if(!store.bounty){
                store.bounty = 0;
            }
            //遍历扣除每个参与者的积分
            async.eachSeries(users, function(user, callback){
                user.score = (user.score ? user.score : 0 ) - Setting.get('enrollScore');
                console.log('扣除参与对战所需的报名积分:' + user.score);
                user.save(function(err){
                    if(err) {
                        console.log(err);
                    }
                    store.bounty = store.bounty + Setting.get('enrollScore');
                    console.log('题库的悬赏分增加到' + store.bounty);
                    callback(err);
                });
            }, function(err){
                if(err){
                    console.log(err);
                }
                console.log('更新题库的悬赏分:' + store.bounty);
                store.save(function(err){
                    if(err) throw err;
                    res.send({
                        status: 'I'
                    });
                });
            });
        }
    });
});

/**
 * 更新对战数据
 * @param userId
 * @param battle
 * @param myScore
 * @param fleeUsers
 * @param res
 */
var updateBattleData = function(userId, battle, myScore, totalScore, fleeUsers, req, res){

    Store.findById(battle.store).populate('bestUser').exec(function(err, store){
        if(err) throw err;

        console.log(store);
        //打破记录
        var bestScore = store.bestScore || 0;

        console.log('bestScore' + bestScore);
        console.log('myScore' + myScore);
        console.log('totalScore' + totalScore);

        //得分达到及格线才算成功
        var success = false;
        var succPct = Setting.get('succPct');
        var jigeXian = (totalScore * (succPct / 100)).toFixed(0); //及格线
        if(myScore >= jigeXian){
            success = true;
        }
        if(success && bestScore <= myScore){
            var message = '恭喜您获得积分:'+ store.score + '分，该题库最高分为:' + bestScore + '分';

            //计算悬赏分
            var breakRecordPct = Setting.get('breakRecordPct');
            var bounty = store.bounty || 0;
            var sb = 0;
            if(bounty){
                sb = Math.round(bounty * (breakRecordPct / 100));
                //扣除积分
                bounty = bounty - sb;
            }
            if(store.bestUser){
                console.log(store.bestUser);
                message = '恭喜您以'+ myScore +'的高分，打破了'
                + (store.bestUser._id == userId ? '自己' : store.bestUser.name)
                + '的最高记录'+ bestScore
                + '获得积分' + store.score
                + (sb > 0 ? '，另外还赢得悬赏积分'+ sb : '');
            }
            console.log(message);

            store.bestBattle = battle;
            store.bestUser = userId;
            store.bestScore = myScore;

            if(sb > 0){
                store.bounty = bounty;
            }

            store.save(function(err){
                if(err) throw err;
                //更新个人积分
                User.findById(userId).exec(function(err, user){
                    if(err) throw err;

                    //更新用户积分
                    user.score = (user.score || 0) + store.score + sb;
                    user.battles = (user.battles || 0) + 1;

                    //更新回话中的数据
                    if(req.session.user){
                        req.session.user.score = user.score;
                        req.session.user.battles = user.battles;
                    }

                    if(fleeUsers.length > 0){
                        //保存逃跑用户的记录
                        async.eachSeries(fleeUsers, function(fleeUserId, callback){
                            User.findById(fleeUserId).exec(function(err, fleeUser){
                                if(err) throw err;
                                if(fleeUser){
                                    fleeUser.flee = (fleeUser.flee ? fleeUser.flee : 0) + 1;
                                    fleeUser.save(function(err){
                                       if(err) throw err;
                                        callback(err);
                                    });
                                }else {
                                    callback(err);
                                }
                            });
                        }, function(err){
                            if(err) throw err;
                            //保存用户信息
                            user.save(function(err){
                                if(err) throw err;
                                res.send({
                                    succ : true,//挑战成功
                                    status: 'F',
                                    end: new Date(),
                                    message : message
                                });
                            });
                        });
                    }else {
                        user.save(function(err){
                            if(err) throw err;
                            res.send({
                                succ : true,//挑战成功
                                status: 'F',
                                end: new Date(),
                                message : message
                            });
                        });
                    }
                });
            });
        }else if(success){
            //没能破纪录, 但达到及格线了
            var message = '您的成绩为:'+myScore+'，及格分为:' + jigeXian + '，您获得积分:'+ store.score + '，该题库最高分为:' + bestScore + '分';
            User.findById(userId).exec(function(err, user){
                if(err) throw err;
                user.score = (user.score || 0) + store.score;
                user.battles = (user.battles || 0) + 1;
                //更新回话中的数据
                if(req.session.user){
                    req.session.user.score = user.score;
                    req.session.user.battles = user.battles;
                }
                if(fleeUsers.length > 0) {
                    //保存逃跑用户的记录
                    async.eachSeries(fleeUsers, function (fleeUserId, callback) {
                        console.log('更新逃离人的记录:');
                        console.log(fleeUserId);
                        User.findById(fleeUserId).exec(function (err, fleeUser) {
                            if (err) throw err;
                            if (fleeUser) {
                                fleeUser.flee = (fleeUser.flee ? fleeUser.flee : 0) + 1;
                                fleeUser.save(function (err) {
                                    if (err) throw err;
                                    callback(err);
                                });
                            } else {
                                callback(err);
                            }
                        });
                    }, function (err) {
                        if (err) throw err;
                        //保存用户信息
                        user.save(function (err) {
                            if (err) throw err;
                            res.send({
                                succ : true,//挑战成功
                                status: 'F',
                                end: new Date(),
                                message: message
                            });
                        });
                    });
                }else {
                    user.save(function(err){
                        if(err) throw err;
                        res.send({
                            succ : true,//挑战成功
                            status: 'F',
                            end: new Date(),
                            message : message
                        });
                    });
                }
            });
        }else {
            //未格线
            var message = '您的成绩为'+ myScore +'，未能达到及格线:' + jigeXian;
            User.findById(userId).exec(function(err, user){
                if(err) throw err;
                user.battles = (user.battles || 0) + 1;
                //更新回话中的数据
                if(req.session.user){
                    req.session.user.battles = user.battles;
                }
                if(fleeUsers.length > 0) {
                    //保存逃跑用户的记录
                    async.eachSeries(fleeUsers, function (fleeUserId, callback) {
                        User.findById(fleeUserId).exec(function (err, fleeUser) {
                            if (err) throw err;
                            if (fleeUser) {
                                fleeUser.flee = (fleeUser.flee ? fleeUser.flee : 0) + 1;
                                fleeUser.save(function (err) {
                                    if (err) throw err;
                                    callback(err);
                                });
                            } else {
                                callback(err);
                            }
                        });
                    }, function (err) {
                        if (err) throw err;
                        //保存用户信息
                        user.save(function (err) {
                            if (err) throw err;
                            res.send({
                                succ : false,//挑战失败
                                status: 'F',
                                end: new Date(),
                                message: message
                            });
                        });
                    });
                }else {
                    user.save(function(err){
                        if(err) throw err;
                        res.send({
                            succ : false,//挑战失败
                            status: 'F',
                            end: new Date(),
                            message : message
                        });
                    });
                }
            });
        }
    });
}

//对战技术，记录对战信息，从对战创建人的角度记录，更新更多对战信息
//对战用户信息不用存，每个用户在加入对战的时候已经存入了该信息
router.post('/stop/owner', function (req, res) {

    var query = req.query;
    console.log(query);
    var battleId = query.battleId;
    var userId = query.userId;
    var fleeUsers = query.fleeUsers;
    var allScores = {};
    if(query.allScores){
        allScores = JSON.parse(query.allScores);
    }
    var allResults = {};
    if(query.allResults){
        allResults = JSON.parse(query.allResults);
    }
    var myScore = allScores[userId] || 0;
    if(fleeUsers){
        if(!(fleeUsers instanceof Array)){
            fleeUsers = [fleeUsers];
        }
    }else {
        fleeUsers = [];
    }
    console.log('逃跑用户有：');
    console.log(fleeUsers);
    Battle.findByIdAndUpdate(battleId, {
        fleeUsers: fleeUsers,
        status: 'F',
        end: new Date(),
        allScores: allScores,
        allResults: allResults
    }, {}, function (err, battle) {
        if (err) throw err;
        console.log(battle);

        Paper.findById(battle.paper).exec(function(err, paper){
            if(err) throw err;
            console.log(paper);
            if(paper && paper.totalScore){
                updateBattleData(userId, battle, myScore, paper.totalScore, fleeUsers, req, res);
            }else {
                res.send({
                    succ : false,//挑战失败
                    status: 'F',
                    end: new Date(),
                    message : ''
                });
            }
        });

    });
});

//对战结束，记录对战信息，从参战人员的角度记录，只需记录参战人员的答案
router.post('/stop/user', function (req, res) {

    var query = req.query;
    console.log(query);
    var battleId = query.battleId;
    var userId = query.userId;
    var myScore = 0;
    if(query.myScore){
        myScore = query.myScore;
    }
    var userResults = {};
    if(query.userResults){
        userResults = JSON.parse(query.userResults);
    }
    console.log('userResults');
    console.log(userResults);
    Battle.findById(battleId, function (err, battle) {
        if(!battle.allResults){
            battle.allResults = {};
        }
        battle.allResults[userId] = userResults;
        if(!battle.allScores){
            battle.allScores = {};
        }
        battle.allScores[userId] = myScore;

        battle.save(function(err){
            if(err) throw err;
            console.log(battle);
            Paper.findById(battle.paper).exec(function(err, paper){
                if(err) throw err;
                console.log(paper);
                if(paper && paper.totalScore){
                    updateBattleData(userId, battle, myScore, paper.totalScore, [], req, res);
                }else {
                    res.send({
                        succ : false,//挑战失败
                        status: 'F',
                        end: new Date(),
                        message : ''
                    });
                }
            });
        });
    });
});


//获取试卷内容
router.post('/paper/:paperId', function (req, res) {
    var paperId = req.params.paperId;
    Paper.findById(paperId).populate('questions').exec(function (err, paper) {
        if (err) throw err;
		
        if(paper && paper.questions){
            var questions = paper.questions;
            for (var i = 0, len = questions.length; i < len; i++) {
                var question = questions[i];

                if(question.opts.length == 2){
                    question.text += '(判断题)';
                } else {
                    if(question.answer.length == 1){
                        question.text += '(单选题)';
                    } else {
                        question.text += '(多选题)';
                    }
                }

            }
        }
        res.send(paper);
    });
});


//创建一个练习赛
router.post('/practice/new', function (req, res) {
    var query = req.query;
    console.log(query);
    var storeId = query.storeId;
    //var user = req.session.user;
    var userId = query.userId;
    Store.findOne({
        _id: storeId
    }).exec(function (err, store) {
        if (store) {
            Paper.count({
                store: store._id
            }, function(err, count){
                var random = Math.round(Math.random() * count);
                if(random == count){
                    random = random - 1;
                }
                Paper.find({
                    store: store._id
                }).skip(random).limit(1).exec(function(err, paper){
                    if (err) throw err;
                    if (paper.length > 0) {
                        console.log('随机选择的试卷:' + random + ' ' + paper[0]);
                        var practice = new Practice({
                            store: store,
                            paper: paper[0]._id,
                            user: userId,
                            createTime: new Date()
                        });
                        practice.save(function (err, ppp) {
                            if (err) throw err;
                            console.log('pppppp');
                            console.log(ppp);
                            Practice.findById(practice._id).populate('paper').populate('user').exec(function (err, p) {
                                if (err) throw err;
                                res.send({
                                    succ: true,
                                    practice: p
                                });
                            });
                        });
                    } else {
                        res.send({
                            succ: false,
                            msg: '未找到试卷'
                        });
                    }
                });
            });
        } else {
            res.send({
                succ: false,
                msg: '错误的题库ID'
            })
        }
    });
});

//
router.post('/practice/:practiceId', function(req, res){
    var practiceId = req.params.practiceId;
    console.log(practiceId);
    Practice.findById(practiceId).populate('store').populate('paper').populate('user').exec(function(err, practice){
        if(err) throw err;
        res.send(practice);
    });
});

//开始练习
router.post('/practice/start/:practiceId', function(req, res){
    var practiceId = req.params.practiceId;
    console.log(practiceId);
    Practice.findOneAndUpdate(practiceId, {
        status : 'I',
        start : new Date()
    }, {}, function(err, practice){
        if(err) throw err;
        res.send({
            status: 'I'
        });
    });
});

//结束练习
router.post('/practice/stop/:practiceId', function(req, res){
    var practiceId = req.params.practiceId;
    var query = req.query;
    console.log(query);
    var userId = query.userId;
    var myScore = query.myScore || 0;
    var myResults = query.myResults || [];
    Practice.findById(practiceId).populate('store').populate('paper').exec(function(err, practice){
        if(err) throw err;
        practice.myScore = myScore;
        practice.myResult = myResults;
        var totalScore = practice.paper.totalScore;
        var store = practice.store;
        practice.save(function(err){
            if(err) throw err;
            User.findById(userId).exec(function(err, user){
                if(err) throw err;
                var message = '';
                if((myScore / totalScore) > (Setting.get('succPct') / 100)){//及格了
                    user.score = (user.score || 0) + store.drill;
                    message = '本次练习共赢得积分:' + store.drill + '分';
                }else { //不及格
                    message = '您未能达到及格线，不能获得积分';
                }
                user.practice = (user.practice ? user.practice : 0) + 1;
                if(req.session && req.session.user){
                    req.session.user.score = user.score;
                    req.session.user.practice = user.practice;
                }
                user.save(function(err){
                    if(err) throw err;
                    res.send({
                        status : 'F',
                        score : user.score,
                        message : message
                    });
                });
            });
        });
    });
});


module.exports = router;
